/**
 * 存储当前选择高亮的节点
 */
let activeNodePageVue = null;

// 当前存储解析文件的结果
let compileFileList = []

/**
 * 控制上传列表的节点的数据
 */
const renderUploadList = (list = []) => {
  activeNodePageVue = null;
  compileFileList = [];
  // 上传列表节点
  const uploadFileList = document.getElementById('uploadFileList');
  if(list.length){
    compileFileList = list;
    let html = '';
    list.forEach((v, i)=> {
      html += `<div class="line ${i == 0 ? 'active' : ''}"><div>${v.name}</div><div class="reload">x</div></div>`
    })
    uploadFileList.innerHTML = html;
    // 默认渲染第一个
    renderCodeToDom(list[0]);
    // 事件委托
    eventListener();
  }else{
    uploadFileList.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" width="833.60436" height="638.22869" viewBox="0 0 833.60436 638.22869" class="injected-svg" data-src="https://cdn.undraw.co/illustrations/read-notes_7itt.svg" xmlns:xlink="http://www.w3.org/1999/xlink" role="img" artist="Katerina Limpitsouni" copyright="unDraw" scrapped="true" source="https://undraw.co/"><path d="m20.71637,636.60466c0,.90073.72331,1.62403,1.62403,1.62403h809.63992c.90069,0,1.62403-.72331,1.62403-1.62403s-.72335-1.62403-1.62403-1.62403H22.3404c-.90072,0-1.62403.72331-1.62403,1.62403Z" fill="#2f2e43" stroke-width="0"></path><path d="m440.55989,476.33668c-2.2231,13.47525-13.9493,23.78782-28.04423,23.78782s-25.82109-10.31257-28.04419-23.78782h-71.74861v155.49117h199.58563v-155.49113h-71.74863l.00004-.00004Z" fill="#b6b3c5" stroke-width="0"></path><rect x="316.204" y="631.24777" width="19.72649" height="3.48113" fill="#b6b3c5" stroke-width="0"></rect><rect x="490.84147" y="631.82798" width="19.72649" height="3.48113" fill="#b6b3c5" stroke-width="0"></rect><path d="m813.90439,480.39801H11.12674c-6.13535,0-11.12674-4.99167-11.12674-11.12675V11.12674C0,4.99168,4.99139,0,11.12674,0h802.77765c6.13537,0,11.127,4.99168,11.127,11.12674v458.14456c0,6.13508-4.99171,11.12675-11.127,11.12675v-.00004Z" fill="#2f2e41" stroke-width="0"></path><rect x="20.30667" y="19.72662" width="785.57844" height="443.26583" fill="#fff" stroke-width="0"></rect><rect x="150.90939" y="134.38655" width="207" height="59" fill="currentColor" stroke-width="0"></rect><line x1="169.40939" y1="146.88655" x2="200.76646" y2="146.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="163.88655" x2="338.40939" y2="163.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="388.60485" y1="163.88655" x2="430.05884" y2="163.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="177.74146" x2="243.03994" y2="177.74146" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="263.88655" x2="278.90939" y2="263.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="280.88655" x2="261.90939" y2="280.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="294.74146" x2="243.03994" y2="294.74146" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="206.58976" x2="270.19129" y2="206.58976" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="221.01392" x2="338.40939" y2="221.01392" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="169.40939" y1="237.13503" x2="243.03994" y2="237.13503" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="365.40939" y1="80.88655" x2="365.40939" y2="371.88655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="388.60485" y1="196.38655" x2="675.79127" y2="196.38655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="388.60485" y1="214.41454" x2="556.40939" y2="214.41454" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="388.60485" y1="229.38655" x2="581.04165" y2="229.38655" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line><line x1="388.60485" y1="245.99774" x2="736.40939" y2="245.99774" fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2"></line></svg>
      <div class="notData">暂无数据...</div>
      `;
  }
}

/**
 * 上传文件动作
 */
const uploadSubmitFile = () => {
  const uploadFileBtn = document.getElementById('uploadFileBtn');
  uploadFileBtn.onclick = async () => {
    const inputFile = document.createElement('input');
    inputFile.type = 'file';
    inputFile.accept = '.vue'; // 只接受 .vue 文件
    inputFile.multiple = true; // 允许多个文件同时上传
    inputFile.onchange = () => {
      const files = inputFile.files;
      if (files.length > 0) {
        // 处理上传的文件
        compileFile(files);
      }
    };

    // 触发文件选择对话框
    inputFile.click();
  }
}

/**
 * 解析文件动作
 */
const compileFile = (arrFileHandle) => {
  let fileRenderList = [];
  let computedFileList = Array.from(arrFileHandle);
  computedFileList.forEach(async (file, index) => {
    const fileContent = await file.text();
    // 解析文件内容
    const parsedContent = forMatVueToDesignJson(fileContent);
    fileRenderList.push({
      content: parsedContent,
      name: file.name,
    })

    if(index === computedFileList.length - 1){
      // 渲染页面
      renderUploadList(fileRenderList);
    }
  })
}

/**
 * 渲染节点数据
 */
const renderCodeToDom = (item) => {
  if(!item) return
  activeNodePageVue = item;
  const { content, name } = item;
  // 设置pageJson的展示
  const container = document.getElementById('code');
  container.innerHTML = JSON.stringify(content, null, 2);
  // 设置抬头名称的展示
  const title2 = document.getElementById('title2');
  title2.innerText = name;
}

/**
 * 事件委托机制触发选择切换
 */
const eventListener = () => {
  // 缓存 DOM 元素
  const uploadFileList = document.getElementById('uploadFileList');

  // 定义事件处理函数
  function handleClick(event) {
      // 阻止事件冒泡
      event.stopPropagation();

      const clickedElement = event.target.closest('.line');

      // 检查点击元素是否是删除按钮
      if (event.target.classList.contains('reload')) {
          // 获取当前删除元素的索引
          const targetIndex = Array.from(uploadFileList.children).findIndex(j => j == event.target.closest('.line'));
          // 从数组中移除对应索引的元素
          targetIndex > -1 && compileFileList.splice(targetIndex, 1);
          // 移除父元素
          event.target.closest('.line').remove();
          if(clickedElement && !clickedElement.classList.contains('active')){	return }
          // 如果是选中的元素就默认找下一个元素高亮，如果是最后一个元素且高亮，就找上一个元素高亮，如果只有自己一个元素，就不高亮，需要返回当前高亮节点的索引，用于render函数的渲染
          // 如果没有高亮，就默认高亮第一个元素
          if (uploadFileList.children.length > 0) {
              const activeElement = uploadFileList.querySelector('.active');
              if (!activeElement) {
                  const index = targetIndex;
                  if (index < uploadFileList.children.length - 1) {
                      uploadFileList.children[index].classList.add('active');
                      renderCodeToDom(compileFileList[index])
                  } else if (index == uploadFileList.children.length - 1) {
                      uploadFileList.children[index - 1].classList.add('active');
                      renderCodeToDom(compileFileList[index - 1])
                  } else {
                      uploadFileList.children[0].classList.add('active');
                      renderCodeToDom(compileFileList[0])
                  }
              }
          }else{
            renderUploadList([])
          }
        return;
      }

      // 如果点击的不是子元素，或者子元素不是目标元素，则忽略
      if (!clickedElement || !uploadFileList.contains(clickedElement)) { return; }

      // 移除所有的高亮样式
      const children = Array.from(uploadFileList.children);
      children.forEach(child => {
          child.classList.remove('active');
      });

      // 添加高亮样式到当前点击的元素
      clickedElement.classList.add('active');

      // 获取当前点击的元素的索引
      const index = children.indexOf(clickedElement);

      // 触发渲染
      renderCodeToDom(compileFileList[index])
  }

  // 添加事件委托
  uploadFileList.addEventListener('click', handleClick);
}


/**
 * 复制到粘贴板
 */
const copyToClipboard = () => {
  const copyJson = document.getElementById('copyJson');
  copyJson.onclick = async () => {
    if(!activeNodePageVue){
      alert('请先选择文件');
      return;
    }
    await navigator.clipboard.writeText(JSON.stringify(activeNodePageVue.content, null, 2))
    alert('复制成功！');
  }
  
}

/**
 * 构建页面的脚本代码
 */
const renderPageInit = () => {
  // 绑定按钮事件
  uploadSubmitFile();
  // 展示文件列表事件
  renderUploadList();
  // 绑定复制操作
  copyToClipboard();
}

window.onload = renderPageInit;